
package hackathon.techbooster.tanabata;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class CreateActivity extends Activity implements OnClickListener {
    private static final String TAG = CreateActivity.class.getSimpleName();

// @formatter:off
    EditText mEditName;
    EditText mEditHope;
    CheckBox mCheckTwitter;

    String mId;
    String mName;
    String mHope;
    boolean isTwitter;
// @formatter:on

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);

        mEditName = (EditText) findViewById(R.id.editName);
        mEditHope = (EditText) findViewById(R.id.editHope);
        mCheckTwitter = (CheckBox) findViewById(R.id.chkTwitter);

        final String[] data = PreferenceUtils.getData(this);

        mEditName.setText(data[0]);
        mEditHope.setText(data[1]);
        mCheckTwitter.setChecked(Boolean.valueOf(data[2]));

        findViewById(R.id.btn_create).setOnClickListener(this);
    }

    public class SaveJsonAsync extends AsyncTask<String, Void, String> {

        public SaveJsonAsync() {
            findViewById(R.id.progressbar_area).setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... url) {
            String htmlData;
            try {
                htmlData = getHttpData(url[0]);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            return htmlData;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            findViewById(R.id.progressbar_area).setVisibility(View.GONE);
            if (result != null && !result.trim().equals("")) {
                // プリファレンス保存
                PreferenceUtils.setCreatedId(getApplicationContext(), result.trim(), mName.trim(),
                        mHope.trim(), isTwitter);

                Intent intent = new Intent(CreateActivity.this, ShowListActivity.class);
                intent.putExtra(PreferenceUtils.KEY_TWITTER, isTwitter);
                String tweetMessage = "";
                if (mId.equals("-1")) {
                    tweetMessage = getString(R.string.created_tweet_message);
                } else {
                    tweetMessage = getString(R.string.modified_tweet_message);
                }
                intent.putExtra(PreferenceUtils.KEY_TWEET_MESSAGE, tweetMessage);
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(getApplicationContext(), R.string.error_uploaded, Toast.LENGTH_SHORT)
                        .show();
            }
        }

        private String getHttpData(String url) throws IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            Log.e(TAG, "url=" + url);
            HttpGet request = new HttpGet(url);
            // HttpResponse httpResponse = httpClient.execute(request);

            String result = "";
            try {
                result = httpClient.execute(request, new ResponseHandler<String>() {
                    @Override
                    public String handleResponse(HttpResponse response)
                            throws ClientProtocolException, IOException {
                        // response.getStatusLine().getStatusCode()でレスポンスコードを判定する。
                        // 正常に通信できた場合、HttpStatus.SC_OK（HTTP 200）となる。
                        switch (response.getStatusLine().getStatusCode()) {
                            case HttpStatus.SC_OK:
                                // レスポンスデータを文字列として取得する。
                                // byte[]として読み出したいときはEntityUtils.toByteArray()を使う。
                                return EntityUtils.toString(response.getEntity(), "UTF-8");
                            default:
                                throw new IOException("status error:status="
                                        + response.getStatusLine().getStatusCode());
                        }

                    }
                });

            } catch (ClientProtocolException e) {
                throw new IOException("ClientProtocolException" + e.getStackTrace());
            } finally {
                // ここではfinallyでshutdown()しているが、HttpClientを使い回す場合は、
                // 適切なところで行うこと。当然だがshutdown()したインスタンスは通信できなくなる。
                httpClient.getConnectionManager().shutdown();
            }

            return result;
        }
    }

    @Override
    public void onClick(View v) {
        try {

            mName = mEditName.getText().toString().trim();
            Log.e(TAG, "name=" + mName);
            mHope = mEditHope.getText().toString().trim();
            isTwitter = mCheckTwitter.isChecked();

            if (mName.equals("")) {
                Toast.makeText(this, R.string.error_no_name, Toast.LENGTH_SHORT).show();
            } else if (mHope.equals("")) {
                Toast.makeText(this, R.string.error_hope, Toast.LENGTH_SHORT).show();
            } else {
                mId = PreferenceUtils.getCreatedId(this);
                String encodeName = PreferenceUtils.encodeUrl(mName);
                String encodeHope = PreferenceUtils.encodeUrl(mHope);
                new SaveJsonAsync().execute(getString(R.string.create_url, mId, encodeName,
                        encodeHope));
                Log.d(TAG,
                        getString(R.string.create_url, mId, PreferenceUtils.encodeUrl(mName),
                                PreferenceUtils.encodeUrl(mHope)));
            }
        } catch (UnsupportedEncodingException e) {
            Toast.makeText(this, R.string.error_change_char, Toast.LENGTH_SHORT).show();
        }
    }
}
